﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 生产领料服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class ProductionmaterialrequisitionService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Productionmaterialrequisition> _productionmaterialrequisitionRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public ProductionmaterialrequisitionService(SqlSugarRepository<Productionmaterialrequisition> productionmaterialrequisitionRep, ISqlSugarClient sqlSugarClient)
    {
        _productionmaterialrequisitionRep = productionmaterialrequisitionRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询生产领料 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询生产领料")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<ProductionmaterialrequisitionOutput>> Page(PageProductionmaterialrequisitionInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _productionmaterialrequisitionRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.MaterialRequisitionNumber.Contains(input.Keyword) || u.PickingType.Contains(input.Keyword) || u.Remarks.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.MaterialRequisitionNumber), u => u.MaterialRequisitionNumber.Contains(input.MaterialRequisitionNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PickingType), u => u.PickingType.Contains(input.PickingType.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remarks), u => u.Remarks.Contains(input.Remarks.Trim()))
            .WhereIF(input.ProductsId != null, u => u.ProductsId == input.ProductsId)
            .WhereIF(input.WarehouseId != null, u => u.WarehouseId == input.WarehouseId)
            .WhereIF(input.PickingDatesRange?.Length == 2, u => u.PickingDates >= input.PickingDatesRange[0] && u.PickingDates <= input.PickingDatesRange[1])
            .LeftJoin<Products>((u, products) => u.ProductsId == products.Id)
            .LeftJoin<Warehouse>((u, products, warehouse) => u.WarehouseId == warehouse.Id)
            .Select((u, products, warehouse) => new ProductionmaterialrequisitionOutput
            {
                Id = u.Id,
                MaterialRequisitionNumber = u.MaterialRequisitionNumber,
                ProductsId = u.ProductsId,
                ProductsFkDisplayName = $"{products.ClassifyId}",
                PickingType = u.PickingType,
                WarehouseId = u.WarehouseId,
                WarehouseFkDisplayName = $"{warehouse.WarehouseName}",
                Remarks = u.Remarks,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
                PickingDates = u.PickingDates,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取生产领料详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取生产领料详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Productionmaterialrequisition> Detail([FromQuery] QueryByIdProductionmaterialrequisitionInput input)
    {
        return await _productionmaterialrequisitionRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加生产领料 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加生产领料")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddProductionmaterialrequisitionInput input)
    {
        var entity = input.Adapt<Productionmaterialrequisition>();
        return await _productionmaterialrequisitionRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新生产领料 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新生产领料")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateProductionmaterialrequisitionInput input)
    {
        var entity = input.Adapt<Productionmaterialrequisition>();
        await _productionmaterialrequisitionRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除生产领料 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除生产领料")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteProductionmaterialrequisitionInput input)
    {
        var entity = await _productionmaterialrequisitionRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _productionmaterialrequisitionRep.FakeDeleteAsync(entity);   //假删除
        //await _productionmaterialrequisitionRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除生产领料 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除生产领料")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteProductionmaterialrequisitionInput> input)
    {
        var exp = Expressionable.Create<Productionmaterialrequisition>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _productionmaterialrequisitionRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _productionmaterialrequisitionRep.FakeDeleteAsync(list);   //假删除
        //return await _productionmaterialrequisitionRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataProductionmaterialrequisitionInput input)
    {
        var productsIdData = await _productionmaterialrequisitionRep.Context.Queryable<Products>()
            .InnerJoinIF<Productionmaterialrequisition>(input.FromPage, (u, r) => u.Id == r.ProductsId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.ClassifyId}"
            }).ToListAsync();
        var warehouseIdData = await _productionmaterialrequisitionRep.Context.Queryable<Warehouse>()
            .InnerJoinIF<Productionmaterialrequisition>(input.FromPage, (u, r) => u.Id == r.WarehouseId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.WarehouseName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "productsId", productsIdData },
            { "warehouseId", warehouseIdData },
        };
    }
    
    /// <summary>
    /// 导出生产领料记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出生产领料记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageProductionmaterialrequisitionInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportProductionmaterialrequisitionOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "生产领料导出记录");
    }
    
    /// <summary>
    /// 下载生产领料数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载生产领料数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportProductionmaterialrequisitionOutput>(), "生产领料导入模板", (_, info) =>
        {
            if (nameof(ExportProductionmaterialrequisitionOutput.ProductsFkDisplayName) == info.Name) return _productionmaterialrequisitionRep.Context.Queryable<Products>().Select(u => $"{u.ClassifyId}").Distinct().ToList();
            if (nameof(ExportProductionmaterialrequisitionOutput.WarehouseFkDisplayName) == info.Name) return _productionmaterialrequisitionRep.Context.Queryable<Warehouse>().Select(u => $"{u.WarehouseName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入生产领料记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入生产领料记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportProductionmaterialrequisitionInput, Productionmaterialrequisition>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 产品类别
                    var productsIdLabelList = pageItems.Where(x => x.ProductsFkDisplayName != null).Select(x => x.ProductsFkDisplayName).Distinct().ToList();
                    if (productsIdLabelList.Any()) {
                        var productsIdLinkMap = _productionmaterialrequisitionRep.Context.Queryable<Products>().Where(u => productsIdLabelList.Contains($"{u.ClassifyId}")).ToList().ToDictionary(u => $"{u.ClassifyId}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.ProductsId = productsIdLinkMap.GetValueOrDefault(e.ProductsFkDisplayName ?? "");
                            if (e.ProductsId == null) e.Error = "产品类别链接失败";
                        });
                    }
                    // 链接 仓库
                    var warehouseIdLabelList = pageItems.Where(x => x.WarehouseFkDisplayName != null).Select(x => x.WarehouseFkDisplayName).Distinct().ToList();
                    if (warehouseIdLabelList.Any()) {
                        var warehouseIdLinkMap = _productionmaterialrequisitionRep.Context.Queryable<Warehouse>().Where(u => warehouseIdLabelList.Contains($"{u.WarehouseName}")).ToList().ToDictionary(u => $"{u.WarehouseName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.WarehouseId = warehouseIdLinkMap.GetValueOrDefault(e.WarehouseFkDisplayName ?? "");
                            if (e.WarehouseId == null) e.Error = "仓库链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Productionmaterialrequisition>>();
                    
                    var storageable = _productionmaterialrequisitionRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.MaterialRequisitionNumber?.Length > 32, "领料编号长度不能超过32个字符")
                        .SplitError(it => it.Item.PickingType?.Length > 32, "类型长度不能超过32个字符")
                        .SplitError(it => it.Item.Remarks?.Length > 32, "备注长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
